//
//  CalendarCollectionViewController.swift
//  foodApp1
//
//  Created by Jenny Shi on 2018/1/28.
//  Copyright © 2018年 Apple Inc. All rights reserved.
//

import UIKit
import os.log
import Alamofire

class CalendarCollectionViewController: UICollectionViewController {
    
    var params:(key:String,title:String,natureQueryLanguage:[String])?
    
    var selectDate : String = "2018-04-13"
    var selectYyyyMm : Date?

    //暂时取消了"选择方式"这个功能
    @IBOutlet weak var modeSelector: UIBarButtonItem!

    var tag:IndexPath?
    
    var tmpStartDate : Date = Date()
    
    lazy var  dataSourceManager = CalenadrDataSource()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        dataSourceManager.startDate = tmpStartDate
        
        self.collectionView?.allowsSelection = true
        self.collectionView?.allowsMultipleSelection = true

        //自定义导航栏右侧的+按钮
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "+", style: UIBarButtonItemStyle.plain, target: self, action: #selector(CalendarCollectionViewController.addEvent))
        
        //自定义导航栏左侧的cancel按钮
        let barButtonItem = UIBarButtonItem(title: "<", style: .plain, target: self, action: #selector(CalendarCollectionViewController.cancelButtonClicked))
        self.navigationItem.leftBarButtonItem = barButtonItem
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    @IBAction func lastMonthButtonClicked(_ sender: UIButton) {
        tmpStartDate = tmpStartDate - 30*24*60*60
        dataSourceManager.startDate = tmpStartDate
        self.collectionView?.reloadData()
    }
    
    @IBAction func nextMonthButtonClicked(_ sender: UIButton) {
        tmpStartDate = tmpStartDate + 30*24*60*60
        dataSourceManager.startDate = tmpStartDate
        self.collectionView?.reloadData()
    }
    
    @IBAction func addButtonClicked(_ sender: UIButton) {
        addEvent()
    }
    
    
    //MARK: 导航栏左上角的cancel返回键
    @objc func cancelButtonClicked() {
        if let owningNavigationController = navigationController{
            owningNavigationController.popViewController(animated: true)
        }else {
            fatalError("The ViewController is not inside a navigation controller.")
        }
    }
    
    //MARK: 导航栏右上角的+键，创建event
    @objc func addEvent() {
        performSegue(withIdentifier: "dateToAddEvent", sender: self)
    }
    
    
    //暂时取消了这个功能
    @IBAction func selectedMode(_ sender: UIBarButtonItem) {
        
    }

    // MARK: - Navigation
     
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        super.prepare(for: segue, sender: sender)
        switch(segue.identifier ?? "") {
        case "dateToAddEvent":
            os_log("Adding a new event from date selector", log: OSLog.default, type: .debug)
            guard let EventDetailViewController = segue.destination as? Calendar1Detail else {
                fatalError("Unexpected destination: \(segue.destination)")
            }
            //取当前位置的日期，传到下一屏。dateStringFromDate只取年月，StringDayFromDate取日
            EventDetailViewController.sourceViewControllerType = 1
        case "dateToEventList":
            os_log("dateToEventList", log: OSLog.default, type: .debug)
            guard let eventListViewController = segue.destination as? EventListViewController else {
                fatalError("Unexpected destination: \(segue.destination)")
            }
            //取当前位置的日期，传到下一屏。dateStringFromDate只取年月，StringDayFromDate取日
            var dayStr = dataSourceManager.StringDayFromDate(selectYyyyMm!)
            let dayLen = (dayStr as NSString).length
            if dayLen < 2 {
                dayStr = "0" + dayStr
            }
            selectDate =  dataSourceManager.dateStringFromDate(selectYyyyMm!) + "-" + dayStr
            eventListViewController.dateTitle = selectDate
            eventListViewController.dateSelect = selectYyyyMm
        default:
            fatalError("Unexpected Segue Identifier; \(String(describing: segue.identifier))")
        }
    }

    @IBAction func unwindToCalendarDateSelector(sender: UIStoryboardSegue) {
   
        let sourceViewController = sender.source as? Calendar1Detail
        let cuEvent = sourceViewController?.cuEvent
        print(cuEvent!)
        
    }

    
    // MARK: UICollectionViewDataSource
    
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return dataSourceManager.monthCount
    }
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return dataSourceManager.daysInMonth(section)
    }
    
    //Daycell，具体的某天
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DayCell", for: indexPath)
        
        let (date,dayState) = dataSourceManager.dayState(indexPath)
        
        if let button = cell.viewWithTag(1) as? RoundBackgroundLabel
        {
            button.backRoundColor = UIColor.lightGray
            button.isHidden = dayState.contains(.NotThisMonth)
            guard !button.isHidden else{
                return cell
            }
            button.text = dataSourceManager.StringDayFromDate(date)
            guard !dayState.contains(.UnSelectable) else{
                button.textColor = UIColor.lightGray
                button.roundType = .none
                return cell
            }
            
            //此时灰色圆圈不包括aaa及下面的button图标
            if let detail = cell.viewWithTag(2) as? UILabel{
//                detail.text = "aaa"
                detail.textColor = UIColor.green
            }
            //后面的括号中是未处理的邀请数
//            button.text = dataSourceManager.StringDayFromDate(date) + "(1)"
            button.text = dataSourceManager.StringDayFromDate(date)
            button.roundType = dayState.roundType
            
            if dayState.contains(.Selected){
                if dayState.contains(.Today){
                    button.textColor = UIColor.red
                }else{
                    button.textColor = UIColor.white
                }
            }else{
                if dayState.contains(.Today){
                    button.textColor = UIColor.red
                }else{
                    button.textColor = UIColor.black
                }
            }
        }
        
        return cell
    }
    
    //SectionCell，年月标题
    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView
    {
        let cell = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "SectionCell", for: indexPath)
        if let label = cell.viewWithTag(1) as? UILabel
        {
            label.text = dataSourceManager.dateStringFromDate(dataSourceManager.monthState((indexPath as NSIndexPath).section))
        }
        return cell
    }
    
    // MARK: UICollectionViewDelegate
    
    /*
     // Uncomment this method to specify if the specified item should be highlighted during tracking
     override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
     return true
     }
     */
    
    //Uncomment this method to specify if the specified item should be selected
    //    override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
    //        let (_,dayState) = dataSourceManager.dayState(indexPath)
    //        if dayState.contains(.NotThisMonth) || dayState.contains(.UnSelectable){
    //            return false
    //        }
    //        return true
    //    }
    //
    
    //选中一个日期，然后通过dateToCalendar转到Calendar。注意，此处取到选定日期，并通过prepare传到Calendar模块
    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        didCellClick(indexPath)
        selectYyyyMm = dataSourceManager.dateOfIndexPath(indexPath)
        self.performSegue(withIdentifier: "dateToEventList", sender: self)
    }
    
    override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        didCellClick(indexPath)
    }
    
    func didCellClick(_ indexPath: IndexPath){
        let (_,dayState) = dataSourceManager.dayState(indexPath)
        if dayState.contains(.NotThisMonth) || dayState.contains(.UnSelectable){
            return
        }
        if dataSourceManager.didSelectItemAtIndexPath(indexPath){
            self.collectionView?.reloadData()
        }
    }

}

